<template>
  <div>
    <h3 text-center m-0 mb-20px></h3>
    <el-form ref="loginFormRef" :model="loginFormData" :rules="loginRules" size="large">
      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input v-model.trim="loginFormData.username" :placeholder="loginTexts.username">
          <template #prefix>
            <el-icon>
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-tooltip :visible="isCapsLock" :content="t('login.capsLock')" placement="right">
        <el-form-item prop="password">
          <el-input
            v-model.trim="loginFormData.password"
            :placeholder="loginTexts.password"
            type="password"
            show-password
            @keyup="checkCapsLock"
            @keyup.enter="handleLoginSubmit"
          >
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-tooltip>

      <!-- 验证码 -->
      <el-form-item prop="captchaCode">
        <div flex>
          <el-input
            v-model.trim="loginFormData.captchaCode"
            :placeholder="loginTexts.captchaCode"
            @keyup.enter="handleLoginSubmit"
          >
            <template #prefix>
              <div class="i-svg:captcha" />
            </template>
          </el-input>
          <div cursor-pointer h="[40px]" w="[120px]" flex-center ml-10px @click="getCaptcha">
            <div v-if="codeLoading" class="flex-center">
              <el-icon class="is-loading">
                <Loading />
              </el-icon>
            </div>
            <img
              v-else
              object-cover
              border-rd-4px
              p-1px
              shadow="[0_0_0_1px_var(--el-border-color)_inset]"
              :src="captchaBase64"
              :alt="t('login.captchaCode')"
            />
          </div>
        </div>
      </el-form-item>

      <!-- 租户选择 -->
      <el-form-item prop="tenantId">
        <el-select v-model="loginFormData.tenantId" :placeholder="loginTexts.tenant" class="w-full">
          <el-option
            v-for="tenant in tenantList"
            :key="tenant.id"
            :value="tenant.id"
            :label="tenant.name"
          />
        </el-select>
      </el-form-item>

      <div class="flex-x-between w-full">
        <el-checkbox v-model="loginFormData.rememberMe">{{ loginTexts.rememberMe }}</el-checkbox>
        <el-link type="primary" :underline="false" @click="toOtherForm('resetPwd')">
          {{ loginTexts.forgetPassword }}
        </el-link>
      </div>

      <!-- 登录按钮 -->
      <el-form-item>
        <el-button :loading="loading" type="primary" class="w-full" @click="handleLoginSubmit">
          {{ loginTexts.login }}
        </el-button>
      </el-form-item>
    </el-form>

    <div flex-center gap-10px>
      <el-text size="default">{{ loginTexts.noAccount }}</el-text>
      <el-link type="primary" :underline="false" @click="toOtherForm('register')">
        {{ loginTexts.reg }}
      </el-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from "element-plus";
import { LocationQuery, RouteLocationRaw, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import AuthAPI, { type LoginFormData, TenantInfo } from "@/api/auth.api";
import router from "@/router";
import { useUserStore } from "@/store";
import { computed, onMounted, ref } from "vue";

const { t } = useI18n();
const userStore = useUserStore();
const route = useRoute();

const loginTexts = computed(() => ({
  login: t("login.login"),
  username: t("login.username"),
  password: t("login.password"),
  captchaCode: t("login.captchaCode"),
  rememberMe: t("login.rememberMe"),
  forgetPassword: t("login.forgetPassword"),
  noAccount: t("login.noAccount"),
  reg: t("login.reg"),
  tenant: t("login.tenant"),
}));

const loginFormRef = ref<FormInstance>();
const loading = ref(false); // 按钮 loading 状态
const isCapsLock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串

const loginFormData = ref<LoginFormData>({
  username: "admin",
  password: "123456",
  captchaKey: "",
  captchaCode: "",
  rememberMe: false,
  tenantId: null,
});

const tenantList = ref<TenantInfo[]>([]); // 租户列表

const createRule = (field: string, required: boolean, min?: number) => {
  const rules = [
    {
      required,
      trigger: "blur",
      message: t(`login.message.${field}.required`),
    },
  ];
  if (min) {
    rules.push({
      min,
      message: t(`login.message.${field}.min`),
      trigger: "blur",
    });
  }
  return rules;
};

const loginRules = computed(() => ({
  username: createRule("username", true),
  password: createRule("password", true, 6),
  captchaCode: createRule("captchaCode", true),
  tenantId: createRule("tenantId", true), // 添加租户 ID 验证规则
}));

const codeLoading = ref(false);

async function getCaptcha() {
  try {
    codeLoading.value = true;
    const data = await AuthAPI.getCaptcha();
    loginFormData.value.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64;
  } catch (error) {
    console.error("获取验证码失败:", error);
  } finally {
    codeLoading.value = false;
  }
}

onMounted(async () => {
  await getCaptcha();
  await fetchTenantList(); // 获取租户列表
});

async function fetchTenantList() {
  try {
    const response = await AuthAPI.getTenantList(); // 假设后端提供了一个获取租户列表的接口
    tenantList.value = response;
  } catch (error) {
    console.error("获取租户列表失败:", error);
  }
}

async function handleLoginSubmit() {
  try {
    const valid = await loginFormRef.value?.validate();
    if (!valid) return;

    loading.value = true;

    await userStore.login(loginFormData.value);
    await userStore.getUserInfo();

    const redirect = resolveRedirectTarget(route.query);
    await router.push(redirect);
  } catch (error) {
    await getCaptcha();
    console.log("登录失败:", error);
  } finally {
    loading.value = false;
  }
}

function resolveRedirectTarget(query: LocationQuery): RouteLocationRaw {
  const defaultPath = "/";
  const rawRedirect = (query.redirect as string) || defaultPath;
  try {
    const resolved = router.resolve(rawRedirect);
    return {
      path: resolved.path,
      query: resolved.query,
    };
  } catch {
    return { path: defaultPath };
  }
}

function checkCapsLock(event: KeyboardEvent) {
  if (event instanceof KeyboardEvent) {
    isCapsLock.value = event.getModifierState("CapsLock");
  }
}

const emit = defineEmits(["update:modelValue"]);

function toOtherForm(type: "register" | "resetPwd") {
  emit("update:modelValue", type);
}
</script>
